package com.cunyu.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.AsyncClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;


public class HttpUtil {
	public static Log logger = LogFactory.getLog("HttpUtil");
	static SimpleClientHttpRequestFactory schr = new SimpleClientHttpRequestFactory();
	static{
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.initialize();
		schr.setTaskExecutor(executor);
		schr.setConnectTimeout(20000);
		schr.setReadTimeout(20000);
	}
	
	public static String postJson(String url,String charset, Map<String, String> params){
		try{
			URI uri = new URI(url);
			AsyncClientHttpRequest request = schr.createAsyncRequest(uri, HttpMethod.POST);
			request.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
			request.getBody().write(serialize(params).getBytes(charset));
			ListenableFuture<ClientHttpResponse> future  = request.executeAsync();
			ClientHttpResponse respone = future.get(20, TimeUnit.SECONDS);
			if(respone.getRawStatusCode() ==200){
				InputStream in =  respone.getBody();
				String res = IOUtils.toString(in, charset);
				in.close();
				return res;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String exec(AsyncClientHttpRequest request){
		try{
			ListenableFuture<ClientHttpResponse> future  = request.executeAsync();
			ClientHttpResponse respone = future.get(20, TimeUnit.SECONDS);
			if(respone.getRawStatusCode() ==200){
				InputStream in =  respone.getBody();
				String res = IOUtils.toString(in, "UTF-8");
				in.close();
				return res;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static ClientHttpResponse execRes(AsyncClientHttpRequest request){
		try{
			ListenableFuture<ClientHttpResponse> future  = request.executeAsync();
			ClientHttpResponse respone = future.get(20, TimeUnit.SECONDS);
			return respone;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static AsyncClientHttpRequest createRequest(String url, HttpMethod method) throws URISyntaxException, IOException{
		URI uri = new URI(url);
		return schr.createAsyncRequest(uri, method);
	}
	
	public static String postParams(String url,String charset, Map<String, String> params){
		try{
			URI uri = new URI(url);
			AsyncClientHttpRequest request = schr.createAsyncRequest(uri, HttpMethod.POST);
			request.getHeaders().set("Content-Type", "application/x-www-form-urlencoded");
			request.getBody().write(toString(params).getBytes(charset));
			ListenableFuture<ClientHttpResponse> future  = request.executeAsync();
			ClientHttpResponse respone = future.get(10, TimeUnit.SECONDS);
			if(respone.getRawStatusCode() ==200){
				InputStream in =  respone.getBody();
				String res = IOUtils.toString(in, charset);
				in.close();
				return res;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getStr(String url, String charset){
		logger.info(url);
		try{
			URI uri = new URI(url);
			AsyncClientHttpRequest request = schr.createAsyncRequest(uri, HttpMethod.GET);
			request.getHeaders().set("content-type","text/html; charset="+charset);
			ListenableFuture<ClientHttpResponse> future  = request.executeAsync();
			ClientHttpResponse respone = future.get(10, TimeUnit.SECONDS);
			if(respone.getRawStatusCode() ==200){
				InputStream in =  respone.getBody();
				String res = IOUtils.toString(in, charset);
				in.close();
				return res;
			}
		}catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return null;
	}
	
	
	public static Object deserialize(String str){
		return JSON.parseObject(str, HashMap.class);
	}
	
	public static String serialize(Object obj){
		try{
			return JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static String encode(String url) {
		try {
			return URLEncoder.encode(url, "utf8");
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String toString(Map<String, String> params){
		StringBuffer buffer = new StringBuffer();
		for(String key: params.keySet()){
			if(buffer.length()>0){
				buffer.append("&");
			}
			buffer.append(key).append("=").append(encode(params.get(key)));
		}
		return buffer.toString();
	}
	
	
	public static String remoatUplod(File file, String folder) throws URISyntaxException, IOException {
		String url = "http://118.190.65.90:7070/uploadbybyte?folder=" + folder;
		AsyncClientHttpRequest request = HttpUtil.createRequest(url, HttpMethod.POST);
		request.getHeaders().add("cookie", "agent=Web; token=-975993958238790062");
		request.getHeaders().add("content-type", "application/octet-stream");
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		IOUtils.copy(new FileInputStream(file), out);
		request.getBody().write(out.toByteArray());
		return HttpUtil.exec(request);
	}
	
	
	public static void main(String[] args) throws InterruptedException, URISyntaxException, IOException {
		System.out.println(remoatUplod(new File("D:/123.png"), "servicep"));
	}
	
}
